#!/usr/bin/perl

use lib::abs qw( base_lib lib );
use JIP::ToolSet; # load my commonly-used modules in a single import

use File::Spec::Functions qw( catfile ); # CPAN modules
use FindBin qw( $RealBin );              #

use Configurator;                # base lib
use Log;                         #
use Proc::Lock;                  #
use JIP::Utils qw( getLogName ); #

use DB::Schema;                                    # searcher custom modules
use Net::SubnetScan qw( findActiveHostsInSubnet ); #

#-- init settings --------------------------------------------------------------
my $conf = Configurator->new( conf => 'robo_conf.pm' )->getSettings;

#-- init log -------------------------------------------------------------------
our $log = Log->new(
    log_file  => catfile( $conf->slow_scanner->log_dir, getLogName() ),
    log_level => $conf->slow_scanner->log_level,
);

#-- signal handlers ------------------------------------------------------------
require( catfile( $RealBin, 'signal_handlers.pl' ) );

#-- check lock -----------------------------------------------------------------
$log->Note('setup lock');

my $process = Proc::Lock->new( lock_file => $conf->slow_scanner->lock_file );

$process->lock;

#-- orm handle -----------------------------------------------------------------
my $orm = DB::Schema->connect(
    $conf->sql->dsn,
    $conf->sql->user,
    $conf->sql->pass,
);

$orm->storage->debug( $conf->sql->isDebug );

#-- main -----------------------------------------------------------------------
my @knownHosts = $orm->resultset('Ftphosts')->get_column('hostip')->all;

foreach my $eachSubnetMask ( @{ $conf->slow_scanner->networks } ) {
    $log->Note( 'network '. $eachSubnetMask );

    foreach my $eachIPAddress ( findActiveHostsInSubnet( $eachSubnetMask ) ) {
        if ( $eachIPAddress ~~ @knownHosts ) {
            $log->Note( 'host: '. $eachIPAddress );
        }
        else {
            $log->Note( 'new host: '. $eachIPAddress );

            $orm->resultset('Ftphosts')->create( { hostip => $eachIPAddress } );

            push @knownHosts, $eachIPAddress;
        }
    }
}

#-- finalyze -------------------------------------------------------------------
$log->Note('-- finalyze -----------------------------------------------------');

$log->Note('unset lock...') and $process->unlock;

$log->Note('exiting');

#-- end ------------------------------------------------------------------------
